<script setup>
import { ref, reactive, toRaw } from 'vue'
import { useRouter } from 'vue-router';
import { useStore } from '../../store/store'
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href
import { getCode, userAuthentication,userLogin,menuPermissions } from '../../api/index'

const store = useStore()

const router = useRouter()

// true 表示登录 false 表示注册
const isToggle = ref(true)

// 登录表单数据
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode: '',
})

// 发送短信
const countdown = reactive({
  validText: '获取验证码',
  time: 60,
})
// 判断是否发送验证码
let flag = false
// 表单验证规则
const rules = reactive({
  userName: [{ validator: validatorUser, trigger: 'blur' }],
  passWord: [{ validator: validatorPwd, trigger: 'blur' }],
})

// 校验手机号
function validatorUser(rule, value, callback) {
  // 不能为空
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value)
      ? callback()
      : callback(new Error('请输入正确的手机号'))
  }
}

// 校验密码
function validatorPwd(rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const pwdReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/
    pwdReg.test(value)
      ? callback()
      : callback(new Error('密码格式为8-16位，包含大小写字母和数字'))
  }
}

// 切换登录和注册
function handleChange() {
  isToggle.value = !isToggle.value
}

// 发送验证码
function countdownChange() {
  // 是否以发送
  if (flag) {
    return
  }
  // 判断手机号是否正确
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/

  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: '请输入正确的手机号',
      type: 'warning',
    })
  }

  // 倒计时
  const time = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.validText = '获取验证码'
      countdown.time = 60
      flag = false
      // 清除倒计时
      clearInterval(time)
    } else {
      countdown.time--
      countdown.validText = `剩余${countdown.time}秒`
    }
  }, 1000)
  flag = true
  getCode({ tel: loginForm.userName }).then(({ data }) => {
    if (data.code === 10000) {
      ElMessage.success('发送成功')
    } else {
      ElMessage.error(data.msg)
    }
  },(err) => {
    console.log(err)
  })
}

// 表单ref
const loginFormRef = ref()
// 提交表单
async function submitForm(formEl) {
  if(!formEl) return
  // 手动触发校验
  await formEl.validate(async (valid, fields) => {
    if(valid) {
      if(isToggle.value) {
        // 登录
        const {data} = await userLogin(loginForm)
        if(data.code !== -1) {
          ElMessage.success('登录成功')
          // 存储token
          localStorage.setItem('pz_token', data.data.token)
          // 存储用户信息
          localStorage.setItem('userInfo', JSON.stringify( data.data.userInfo))
          // 获取动态权限路由
          menuPermissions().then(({data}) => {
            store.dynamicMenu(data.data)
            toRaw(store.routerList).forEach(item => {
              router.addRoute('Home', item)
            })
            // 跳转
            router.push({path: '/'})
          })
          
        } else {
          ElMessage.error(data.message)
        }
      } else {
        // 注册用户
        const {data} = await userAuthentication(loginForm)

        if(data.code !== -1) {
          ElMessage.success('注册成功, 请登录')
          //切换至登录
          handleChange()
        } else {
          ElMessage.error(data.message)
        }
      }
    } else {
      console.log('error submit', fields)
    }
  })
}
</script>

<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link @click="handleChange">{{
          isToggle ? '点击注册' : '返回登录'
        }}</el-link>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules">
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            prefix-icon="UserFilled"
          ></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            placeholder="请输入密码"
            prefix-icon="Lock"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="validCode" v-if="!isToggle">
          <el-input
            v-model="loginForm.validCode"
            placeholder="验证码"
            prefix-icon="Lock"
          >
            <template #append>
              <span class="el-input__suffix-inner" @click="countdownChange">{{
                countdown.validText
              }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <!-- 登录按钮 -->
          <el-button
            @click="submitForm(loginFormRef)"
            style="width: 100%"
            type="primary"
            >{{ isToggle ? '登录': '注册' }}</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
  .el-input__suffix-inner {
    cursor: pointer;
  }
}
</style>
